package com.yl.nettylearning.netty.day06;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author yangl
 */
public class HeartServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            /**
                             * 加入 netty 提供的 IdleStateHandler
                             * 1、IdleStateHandler 是netty提供的处理空闲状态的处理器
                             * 2、long readerIdleTime：表示多长时间没有读，就会发送一个心跳检测包检测是否连接
                             * 3、long writerIdleTime：表示多长时间没有写，就会发送一个心跳检测包检测是否连接
                             * 4、long allIdleTime：表示多长时间没有读写，就会发送一个心跳检测包检测是否连接
                             * 5、当IdleStateHandler 触发后，就会传递给下一个handler去处理（通过
                             * 调用下一个handler 的userEventTriggered， 在该方法中处理IdleStateHandler（读空闲，写空闲，读写空闲））
                             */
                            pipeline.addLast(new IdleStateHandler(3,5,7, TimeUnit.SECONDS));
                            //加入对空闲检测处理的handler
                            pipeline.addLast(new HeartServerHandler());
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(1000).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
